#include "widget.h"
#include "./ui_widget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 捕获所有键盘输入, 否则不会捕获上下左右按键
    grabKeyboard();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() != Qt::LeftButton) { // not click left button
        return;
    }
    QPoint point = event->pos(); // 相对Widget的位置
    QPointF relaPoint = event->position();
    QPointF winPoint = event->scenePosition();
    QPointF globPoint = event->globalPosition();
    QString str = QString::asprintf("pos()=(%d, %d)", point.x(), point.y());
    str += QString::asprintf("\nposition()=(%.0lf, %.0lf)", relaPoint.x(), relaPoint.y());
    str += QString::asprintf("\nscenePosition()=(%.0lf, %.0lf)", winPoint.x(), winPoint.y());
    str += QString::asprintf("\nglobalPos()=(%.0lf, %.0lf)", globPoint.x(), globPoint.y());

    ui->labMove->setText(str);
    ui->labMove->adjustSize();
    ui->labMove->move(event->pos());

    QWidget::mousePressEvent(event);
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    QPoint point = ui->btnMove->pos(); // relative position
    if (event->key() == Qt::Key_A || event->key() == Qt::Key_Left) {
        ui->btnMove->move(point.x() - 20, point.y());
    }

    if (event->key() == Qt::Key_D || event->key() == Qt::Key_Right) {
        ui->btnMove->move(point.x() + 20, point.y());
    }

    if (event->key() == Qt::Key_W || event->key() == Qt::Key_Up) {
        ui->btnMove->move(point.x(), point.y() - 20);
    }

    if (event->key() == Qt::Key_S || event->key() == Qt::Key_Down) {
        ui->btnMove->move(point.x(), point.y() + 20);
    }

    QWidget::keyPressEvent(event);
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.drawPixmap(0, 0, width(), height(),
                       QPixmap(":/pics/images/background.jpg"));
}

void Widget::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton result = QMessageBox::question(
        this, "消息框", "确定要退出吗?",
        QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

    if (result == QMessageBox::Yes) {
        event->accept();
    }
    else {
        event->ignore();
    }
}
